#pragma once

#include <robuffer.h>

using namespace Platform;
using namespace Windows::Storage::Streams;

INTEROP_NAMESPACE_BEGIN

class BufferExtensions abstract sealed
{
public:
	static uint8 *GetUnderlyingArray(IBuffer^ buffer)
	{
		IInspectable *inspectable = (IInspectable *)reinterpret_cast<IInspectable *>(buffer);

		Microsoft::WRL::ComPtr<IBufferByteAccess> spBuffAccess;
		HRESULT hr = inspectable->QueryInterface(__uuidof(IBufferByteAccess), (void **)&spBuffAccess);

		uint8 *pReadBuffer = nullptr;
		spBuffAccess->Buffer(&pReadBuffer);

		return pReadBuffer;
	}

	static IBuffer^ CreateFromArray(uint8 *pArray, uint32 size)
	{
		IBuffer^ buffer = ref new Buffer(size);
		uint8 *pInnerArray = GetUnderlyingArray(buffer);

		errno_t err = memcpy_s(pInnerArray, size, pArray, size);
		if (0 != err)
			throw ref new InvalidArgumentException();

		return buffer;
	}
};

INTEROP_NAMESPACE_END
